/**
	This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
package br.biofoco.p2p.peer;

import java.io.Serializable;
import java.math.BigInteger;

import org.codehaus.jackson.map.annotate.JsonDeserialize;
import org.codehaus.jackson.map.annotate.JsonSerialize;

@JsonSerialize(using = CustomIDSerializer.class)
@JsonDeserialize(using = CustomIDDeserializer.class)
public class ID implements Comparable<ID>, Serializable {

	private static final long serialVersionUID = -8684130279915421775L;
	private BigInteger id;
			
	protected ID(BigInteger data){
		this.id = data;
	}
	
	ID(byte[] data){
		data = clone(data);
		if (data == null)
			throw new IllegalArgumentException("data cannot be null!");
		this.id = new BigInteger(data).abs();
	}
	
	private byte[] clone(byte[] src){
		byte[] dst = new byte[src.length];
		System.arraycopy(src, 0, dst, 0, src.length);
		return dst;
	}
	
	@Override
	public boolean equals(Object obj){
		if (this == obj)
			return true;
		if (!(obj instanceof ID))
			return false;
		return ((ID)obj).id.equals(id);
	}
	
	@Override
	public int hashCode() {
		return id.hashCode();
	}
	
	@Override
	public String toString() {
		return id.toString(16);
	}
	
	public int compareTo(ID o) {
		return id.compareTo(o.id);
	}	
	
	public ID plus(long value) {
		return new ID(id.add(new BigInteger(Long.toString(value))));
	}
		
}
